let axios = require('axios')
let qs = require('qs')

axios.defaults.baseURL='http://47.96.154.185:3701';

let baseURL = 'http://47.96.154.185:3701';

function get(url,params,fn) {
    axios.get(url,{params})
    .then(function(res){
        fn(res.data)
    })
    .catch(function(err){
        fn(err)   
    })
}

function post(url,params,fn) {
    axios.post(url,qs.stringify(params))
    .then(function(res){
        fn(res.data)
    })
    .catch(function(err){
        fn(err)   
    })
}



// 请求拦截器---在发送请求之前先 拦截下来,让带点东西,再发送请求 
axios.interceptors.request.use(config=>{
    //在config配置中添加token  
    //获取token
    let token=localStorage.getItem('ygc');
    //判定如果有token就设置 请求头
    if(token){
        config.headers.Authorization='Bearer '+token;
    }

    return config;
});

function getygc(){
    if(!localStorage.getItem('ygc'))window.location.href='/login.html'
}



function uploadpic(key,valve,url,tk,callback){
    let fs = new FormData()

        fs.append(key,valve)
        
        
        let xhr = new XMLHttpRequest()

        xhr.open('post',baseURL+url)
        
        xhr.setRequestHeader('authorization','Bearer'+localStorage.getItem(tk))

        xhr.onreadystatechange = function(){
            if(xhr.readyState==4&&xhr.status==200){
                callback(JSON.parse(xhr.response));
            }
        }
        xhr.send(fs)
}

function Zero(value){
    return value<10?'0'+value:value
}

module.exports = {
    get,
    post,
    getygc,
    baseURL,
    uploadpic,
    Zero
}